function FLogServer () {
    this.data = {};
    this.sector = POgetSector();
    this.notify = {};
    
    var cache = localStorage.getItem ("po_flog_changed_data");
    if (cache && cache.length > 0) {
        this.changed_data = JSON.parse (cache);
    } else {
        this.changed_data = {};
    }
    localStorage.setItem("po_flog_refresh_timestamp", "0");
}

function FLogGetServer () {
    var s = top.flog_server;
    if (s == null || s == undefined) {
        s = top.flog_server = new FLogServer;
    } 
    return s;
}

FLogServer.prototype.LastUpdateAgo = function (lastTimestamp) {
    var ts = this.GetTimestamp ();
    var diff = ts - lastTimestamp;
    
    var ago = "";
    if (diff < 60) {
        ago = diff + " seconds ago";
    } else if (diff < 3600) {
        var min = Math.floor (diff / 60);
        ago = min + " minutes ago";
    } else if (diff < 86400) {
        var hrs = Math.floor (diff / 3600);
        ago = hrs + " hours ago";
    } else {
        var days = Math.floor (diff / 86400);
        var hrs = Math.floor((diff - (days * 86400)) / 3600);
        ago = days + " days and " + hrs + " hours ago"
    }
    return ago;
}

FLogServer.prototype.SetSector = function (sector) {
    this.sector = sector;
    localStorage.setItem("po_flog_refresh_timestamp", "0");
}

FLogServer.prototype.AddNotification = function (name, callback) {
    this.notify[name] = callback;
}

FLogServer.prototype.NotifyAll = function(){
    for (key in this.notify) {
        var callback = this.notify[key];
        if (callback) callback();
    }
}

function RefreshFLogServer () {
    var server = top.FLogGetServer ();
    server.RefreshData ();
//POlog ("Refreshing data");
    setTimeout (RefreshFLogServer, 30000);
}

FLogServer.prototype.GetFacility = function (tileId, type) {
    var tid = Number (tileId);
    var tile = this.data[tid];
    if (tile) {
        if (tile[type])
            return tile[type];//.slice(0);
    }
    tile = this.changed_data[tid];
    if (tile) {
        if (tile[type])
            return tile[type];//.slice(0);
    }
    return {};
}

FLogServer.prototype.GetBuilding = function (tileId, type) {
    var facility = this.GetFacility (tileId, type);
    if (type == "facility")
        facility["facility_type"] = "Building";
    return facility;
}

FLogServer.prototype.GetPlanet = function (tileId, type) {
    var facility = this.GetFacility (tileId, type);
    if (type == "facility")
        facility["facility_type"] = "Planet";
    return facility;
}

FLogServer.prototype.GetStarbase = function (tileId, type) {
    var facility = this.GetFacility (tileId, type);
    if (type == "facility")
        facility["facility_type"] = "Starbase";
    return facility;
}

FLogServer.prototype.SaveFacility = function (tileId, facility, type) {
    var tid = Number (tileId);
    var stamp = this.GetTimestamp();

    facility["timestamp"] = stamp;
    if (!this.data[tid]) this.data[tid] = {};
    if (!this.changed_data[tid]) this.changed_data[tid] = {};
    this.data[tid][type] = facility;
    this.changed_data[tid][type] = facility;
    
    if (facility["navUpdate"] == "delete_others" || facility["navUpdate"] == "delete_all") {
        this.data[tid] = {"facility": this.data[tid]["facility"]};
        this.changed_data[tid] = {"facility": this.changed_data[tid]["facility"]};
    }
    
    var cache = JSON.stringify (this.changed_data);
    localStorage.setItem ("po_flog_changed_data", cache);
//POlog ("Saving facility:"+cache);        
    this.SubmitToServer();
}

FLogServer.prototype.RemoveFacility = function (tileId, facility) {
    var tid = Number (tileId);

    facility["navUpdate"] = "delete_all";
    
    if (this.data) {
        this.data[tid]= {};
    }
    this.changed_data[tid] = {"facility": facility};
    
    var cache = JSON.stringify (this.changed_data);
    localStorage.setItem ("po_flog_changed_data", cache);
//POlog ("Saving facility:"+cache);        
    this.SubmitToServer();
}

FLogServer.prototype.GetTimestamp = function () {
    //var d = new Date();
    //return Math.floor(d.getTime() / 1000)+ (d.getTimezoneOffset()*60);
    var mt = window.milliTime;
    if (!mt)
        mt = top.frames[2].milliTime;
    return Math.floor(mt / 1000);
}

FLogServer.prototype.ClearChanges = function () {
    this.changed_data = {};
    localStorage.removeItem ("po_flog_changed_data");
}

FLogServer.prototype.ClearData = function () {
    this.data = {};
}

FLogServer.prototype.RefreshData = function (callback) {
    var lastTimestamp = Number(localStorage.getItem("po_flog_refresh_timestamp"));
    this.GetFacilitiesBySector (this.sector, "", lastTimestamp, function(data, timestamp) {top.FLogGetServer().RefreshDataCallback(data, timestamp);if(callback){callback();}});
}

FLogServer.prototype.RefreshDataCallback = function (response) {
    var ts = 0;
    
    for (tileId in response) {
        if (!this.data[tileId]) {
            this.data[tileId] = {};
        }
        for (type in response[tileId]) {
            if (!this.data[tileId][type] || response[tileId][type]["timestamp"] > this.data[tileId][type]["timestamp"]) {
//POlog ("Adding:"+tileId+" "+type);
                this.data[tileId][type] = response[tileId][type];
            }
            if (response[tileId][type]["timestamp"] > ts) ts = response[tileId][type]["timestamp"];
        }
    }
    
    for (tileId in response) {
        if (!this.changed_data[tileId]) {
            continue;
        }
        
        for (type in response[tileId]) {
            if (this.changed_data[tileId][type] && response[tileId][type]["timestamp"] > this.changed_data[tileId][type]["timestamp"]) {
                this.changed_data[tileId].slice (type, 1);
            }
        }
        if (this.changed_data[tileId].length == 0) {
            this.changed_data.slice(tileId,1);
        }
    }
    
    var cache = JSON.stringify (this.changed_data);
    localStorage.setItem ("po_flog_changed_data", cache);
    if (ts > 0) {
        localStorage.setItem("po_flog_refresh_timestamp", ts);
        this.NotifyAll ();
//POlog ("Saving TS: "+ts);
    }

    this.SubmitToServer();
}

FLogServer.prototype.SubmitToServer = function () {
    var cache = localStorage.getItem ("po_flog_changed_data");
    if (cache == "{}") return;
    
    if (cache && cache.length > 0) {
        var params = POgetServerParams ();
        params += "&data=" + cache;
//POlog ("Submitting data:"+cache);
    }
    var server = this;
    
    var callback = function (httpRequest) {
//POlog ("po_flog_server: Response: ReadyState:"+httpRequest.readyState+" Status:"+httpRequest.status);
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var response = httpRequest.responseText;
            if (response.replace(/\s/g, "") == "") {
//POlog ("po_flog_server: Empty response received");
            } else if (response.indexOf("po_invalid_user") != -1) {
//POlog ("po_flog_server: Invalid user response received");
            }
            server.ClearChanges ();
//POlog ("po_flog_server: Data arrived:"+response);
        }
    }
    
    POajaxPost (POgetServerUrl ("alerter/flog_save_facility.php"), "POST", params, callback);
}

FLogServer.prototype.GetFacilityByTileId = function(tileId, type, lastTimestamp, callback) {
    var params = POgetServerParams ();
    params += "&call=byTileId";
    params += "&tileId=" + tileId;
    params += "&type=" + type;
    params += "&lastTimestamp=" + lastTimestamp;
    
    var cb = function (httpRequest) {
//POlog ("po_flog_server: Response: ReadyState:"+httpRequest.readyState+" Status:"+httpRequest.status);
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var response = httpRequest.responseText;
            if (response.replace(/\s/g, "") == "") {
//POlog ("po_flog_server: Empty response received");
            } else if (response.indexOf("po_invalid_user") != -1) {
//POlog ("po_flog_server: Invalid user response received");
            }
            callback (JSON.parse(response), lastTimestamp);
//POlog ("po_flog_server: Data arrived:"+response);
        }
    }
    
    POajaxPost (POgetServerUrl ("alerter/flog_get_facility.php"), "GET", params, cb);
}

FLogServer.prototype.GetFacilitiesBySector = function(sector, type, lastTimestamp, callback) {
    var params = POgetServerParams ();
    params += "&call=bySector";
    params += "&sector=" + sector;
    params += "&type=" + type;
    params += "&lastTimestamp=" + lastTimestamp;
    
    var cb = function (httpRequest) {
//POlog ("po_flog_server: Response: ReadyState:"+httpRequest.readyState+" Status:"+httpRequest.status);
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var response = httpRequest.responseText;
            if (response.replace(/\s/g, "") == "") {
//POlog ("po_flog_server: Empty response received");
            } else if (response.indexOf("po_invalid_user") != -1) {
//POlog ("po_flog_server: Invalid user response received");
            }
//POlog ("po_flog_server: Data arrived:"+response);
            callback (JSON.parse(response), lastTimestamp);
        }
    }
    
    POajaxPost (POgetServerUrl ("alerter/flog_get_facility.php"), "GET", params, cb);
}

FLogGetServer ();
setTimeout(RefreshFLogServer, 1000);